<?php
/*------------------------------------------------------------------------
 * Base.php 
 *
 * 基类控制器
 * 	
 * Created on 2017-01-05
 *
 * Author: hwc123 <hwc123@139.com>
 * 
 * Copyright (c) 2017 All rights reserved.
 * ------------------------------------------------------------------------
 */

namespace app\wap\controller;
use \think\Request;
use \think\Controller;

class Base extends Controller{
	public $user_id         = 0;  // 用户ID
	public $user_head_url   = ''; // 用户头像
	public $user_mobile     = ''; // 用户手机号
	public $user_email      = ''; // 用户E-mail
	public $user_nickname   = ''; // 用户昵称
	public $set_password    = ''; // 设置密码
	public $user_city_id    = 0;   // 用户城市ID
	public $user_score      = 0;  // 用户积分
	public $total_num       = 0;  // 总记录数
	public $_pagesize       = 0;  // 每页显示数量
	public $entry_type      = ''; // 入口类型
	public $api;// 接口SDK
	public $is_weixin_visit = false;// 是否微信访问
	public $weixin_openid   = '';// 微信OPENID
	public $is_back_btn     = true;// 显示返回按钮
	public $is_foot_bartab  = true;// 显示底部Bar Tab
	public $password_is_nul = false;// 密码是否设置
	public $is_header_nav   = false;// 显示搜索头部导航
	public $is_header 	    = true;// 头部导航

	// public $_title     = '';// 完整标题
	// public $_cur_title = '';// 当前标题
	// public $_trail     = [];// 
	// public $_pagesize  = 10;// 分页数量
	// public $_user_id   = 0;// 用户ID
	// public $_realname  = '';// 用户姓名
	// public $_nickname  = '';// 用户昵称
	// public $_mobile    = '';// 用户手机号
	
	function _initialize($is_user_login = false){
		// 设置APP类型
		$_SERVER['HTTP_APP_TYPE'] = 'wap';


		//面包导航配置
		// $this->add_step('首页', url('/'));
		
		// 当前URL
		$this->_cur_url = $this->request->url(true);
		$this->assign('_cur_url', $this->_cur_url);
		
		// 网站配置
		$config = model('Config')->_get('', 'system');

		$this->assign('_config', $config);

		// 获取用户信息
		$this->user_id($is_user_login);

		// 设置返回地址
		$back_url = $this->_get('back_url');
		if($back_url){
			$back_url = urldecode($back_url);
			session('back_url', $back_url);
		}
		// 微信OPENID
		$this->weixin_openid = session('weixin_openid');
		
		// 是否微信访问
		if($this->is_weixin_visit()){
			// 微信客服端打开的，则自动登录
			$is_auto_login = $this->_get('is_auto_login');
			$is_auto_login = 1;// 默认自动登录
			// if($this->weixin_openid == 'odKGvwOJG6H8Az9nZ_pgglswqaSQ'){
			// 	// session('weixin_openid', null);exit;
			// }
			if(!$this->weixin_openid && request()->controller() != 'Login' && $is_auto_login && !$this->user_id){
				$jumpurl = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : $this->_cur_url;
				session('login_jumpurl', $jumpurl);
				// var_dump($jumpurl);exit;
				$this->redirect(url('Login/weixin'));
			}
		}

		$this->assign('controller_name', request()->controller());
		$this->assign('action_name', request()->action());
	}
	
	public function checkbox($model_name = '', $where = ''){
		$pk_val = $this->_get('pk_val', '主键val不能为空！');
		$pk_key = $this->_get('pk_key', '主键key不能为空！');
		$field  = $this->_get('field_name', '修改字段不能为空！');

		//使用模型
		$model = db($model_name ? $model_name : $this->request->controller());

		$where[$pk_key] = $pk_val;
		$value = $model->where($where)->value($field);

		$data[$field] = $value ? 0 : 1;
		$model->where($where)->update($data);

		$this->success('设置成功！', '');
	}

	protected function _get($name = '', $empty_msg = '', $default_value = '', $is_array_str = false){
		$value = input($name);
		$value = $this->common_field_check($value, $empty_msg, $default_value, $is_array_str);

		$this->assign(str_replace(array('/a'), '', $name), $value);

		return $value;
	}
	protected function _post($name = '', $empty_msg = '', $default_value = '', $is_array_str = false){
		$value = input($name);
		$value = $this->common_field_check($value, $empty_msg, $default_value, $is_array_str);

		$this->assign(str_replace(array('/a'), '', $name), $value);
		
		return $value;
	}
	/**
	 * 通用字段验证
	 * @param  string $field         参数名
	 * @param  string $empty_msg     值为空，提示信息
	 * @param  string $default_value 值为空，默认值
	 * @param  string $is_array_str  返回数组是否转为字符串，多个以逗号分隔
	 */
	protected function common_field_check($value, $empty_msg = '', $default_value = '', $is_array_str = false){
		if(is_array($value)){
			$array_val = implode(',', $value);
			$is_empty  = empty($array_val);
			$value     = $is_array_str ? $array_val : $value;
		}else{
			$is_empty = !trim($value);
			$value    = trim($value);
		}
		
		if($is_empty && $empty_msg){
			$this->error($empty_msg);
		}
		if($is_empty){
			$value = isset($default_value) ? $default_value : '';
		}

		return $value;
	}
	//操作步骤
	protected function add_step($title, $url = ''){
		$this->_title     = empty($this->_title) ? $title : $title . ' - ' . $this->_title;
		$this->_trail[]   = array('title'=>$title,'url'=>$url);
		$this->_cur_title = $title;
		return $this;
	}
	protected function view($tpl = ''){
		$this->assign('_title', urldecode($this->_title));
		$this->assign('_trail', $this->_trail);
		$this->assign('_cur_title', urldecode($this->_cur_title));
		$this->assign('controller', strtolower($this->request->controller()));
		$this->assign('is_header_nav', $this->is_header_nav);
		$this->assign('is_header', $this->is_header);
		$this->assign('is_foot_bartab', $this->is_foot_bartab);

		return view($tpl);
	}
	// 请求模型
	protected function request(){
		return Request::instance();
	}
	// 是否为Ajax请求
	protected function isAjax(){
		return $this->request->isAjax();
	}
	// 是否为手机访问
	protected function isMobile(){
		return $this->request->isMobile();
	}
	// 是否为GET请求
	protected function isGet(){
		return $this->request->isGet();
	}
	// 是否为POST请求
	protected function isPost(){
		return $this->request->isPost();
	}
	protected function is_weixin_subscribe(){
		$subscribe = 0;
		if($this->weixin_openid){
			import('ThinkWechat', EXTEND_PATH, '.class.php');
			$weixin = new \ThinkWechat('', true);

			$config = model('Config')->_get('', 'weixin');
			$weixin->appid  = $config['appid'];
			$weixin->secret = $config['appsecret'];

			$subscribe = $weixin->get_openid_userinfo($this->weixin_openid, 'subscribe');
			$subscribe = $subscribe ? 1 : 0;
		}
		return $subscribe;
	}
	//判断是否为微信访问
	protected function is_weixin_visit(){
		$this->is_weixin_visit = false;
		if(preg_match("/(MicroMessenger)/si", $_SERVER['HTTP_USER_AGENT'])){
			$this->is_weixin_visit = true;
		}
		$this->assign('is_weixin_visit', $this->is_weixin_visit);
		
		return $this->is_weixin_visit;
	}
	//获取终端类型
	protected function get_app_type(){
		$user_agent = $_SERVER['HTTP_USER_AGENT'];
		// if(preg_match("/(MicroMessenger)/si",$user_agent)){
		//     return 'weixin';
		// }
		if(preg_match("/(Android)/si",$user_agent)){
			return 'android';
		}
		if(preg_match("/(windows phone)/si",$user_agent)){
			return 'wp';
		}
		if(preg_match("/(iPhone|iPad|iPod|iOS)/si",$user_agent)){
			return 'ios';
		}
		return 'pc';
	}

	//获取用户ID
	protected function user_id($is_login = true){
		$user = session('user_info');
		// 强制登录获取用户信息，超时则返回登录界面
		if($is_login){
			$user = model('User')->get_user_info($is_login);
		}

		$this->user                = $user;
		$this->_user_id            = $user['user_id'] ? $user['user_id'] : 0;
		$this->_user_show_name     = $user['show_name'] ? $user['show_name'] : 0;
		$this->_user_head_url      = $user['head_url'] ? $user['head_url'] : '';
		$this->_user_realname      = $user['realname'] ? $user['realname'] : '';
		$this->_user_mobile        = $user['mobile'] ? $user['mobile'] : '';
		$this->_user_email         = $user['email'] ? $user['email'] : '';
		$this->_user_nickname      = $user['nickname'] ? $user['nickname'] : '';
		$this->_user_province_id   = $user['province_id'] ? $user['province_id'] : 0;
		$this->_user_province_name = $user['province_name'] ? $user['province_name'] : 0;
		$this->_user_city_id       = $user['city_id'] ? $user['city_id'] : 0;
		$this->_user_city_name     = $user['city_name'] ? $user['city_name'] : 0;
		$this->_user_area_id       = $user['area_id'] ? $user['area_id'] : 0;
		$this->_user_type          = $user['user_type'] ? $user['user_type'] : 0;//用户类型
		$this->_user_sex           = $user['sex'] ? $user['sex'] : 0;//性别
		$this->_user_bind_info     = $user['bind_info'] ? $user['bind_info'] : '';//绑定信息
		$this->_is_set_password    = $user['is_set_password'];

		$this->assign('user', $user);
		$this->assign('_user_id', $this->_user_id);
		$this->assign('_user_show_name', $this->_user_show_name);
		$this->assign('_user_type', $this->_user_type);
		$this->assign('_user_realname', $this->_user_realname);
		$this->assign('_user_email', $this->_user_email);
		$this->assign('_user_mobile', $this->_user_mobile);
		$this->assign('_is_set_password', $this->_is_set_password);
		$this->assign('_user_city_id', $this->_user_city_id);
		$this->assign('_user_head_url', $this->_user_head_url);

		return $user['user_id'] ? $user['user_id'] : 0;
	}


	// 获取地区数据
	public function get_area_list(){
		$where['parent_id'] = $this->_get('parent_id', '', 0);
		$list = model('Area')->where($where)->order('order_id,area_id')->select();
		$data['list'] = $list;

		$this->success('获取数据成功！', '', $data);
	}

	/**
	 * 获取短信验证码
	 */
	public function get_smscode(){
		$mobile  = $this->_get('mobile', '手机号不能为空！');
		$type    = $this->_get('type', '', 'register');
		$imgcode = $this->_get('imgcode', '图片验证码不能为空！');
		if(!captcha_check($imgcode)){
			$this->error('您输入图片验证码不正确！');
		}
		// $this->success('发送成功，请注意查收！');
		if(model('Sms')->send_smscode($mobile, $type)){
			$this->success('发送成功，请注意查收！');
		}else{
			$this->error(model('Sms')->tips_info);
		}
	}

	/**
	 * 通用列表
	 * @param  string  $model 模型
	 * @param  array   $where where条件
	 * @param  array   $order 排序条件
	 * @param  boolean $return 是否返回数据，返回则不输出模板
	 */
	public function index($model = '', $where = '', $order = '', $query = '', $return = false){
		$model    = model($model ? $model : $this->request->controller());
		$field    = $this->_db_field ? $this->_db_field : '*';
		$join     = $this->_db_join ? $this->_db_join : '';
		$pagesize = $this->_pagesize ? $this->_pagesize : 10;
		if($this->viewFields){
			$model = model('Views');
			$model->viewFields = $this->viewFields;
		}
		$this->_model = $model;
		//使用模板
		$tpl   = $this->_use_tpl ? $this->_use_tpl : $this->request->action();

		//是否字段
		$boolean_field = $this->_boolean_field ? $this->_boolean_field : array('');
		// 主键KEY
		$pk_name = $model->getPk();

		// where条件
		$where = array_merge($where ? $where : array(), $this->_db_where ? $this->_db_where : array());
		if($keyword){$where[$search_field] = array('like',"%$keyword%");}
		if(!$this->viewFields){
			$where['is_delete'] = 0;
		}

		// 排序条件
		$order = $order ? $order : ($this->_db_order ? $this->_db_order . ',' : '') . $pk_name . ' desc';

		$page = $this->_get('page');
		$page = $page ? $page : 1;
		$query['page'] = $page;
		//获取列表数据
		$list = $model->field($field)->join($join)->where($where)->order($order)->paginate($pagesize, false, ['query' => $query]);;

		$surplus = $list->total() % $this->pagesize;
		$except  = $list->total() / $this->pagesize;
		if($surplus < $except){
			$total_page = $surplus + 1;
		}

		if($page >= $total_page){
			$is_hasmore = '';
		}else{
			$is_hasmore = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?page=' . ($page + 1);
		}

		//分页写入模板
		$this->assign('ajax_next_page', $is_hasmore );
		//搜索字段
		$this->assign('search_field', $search_field);
		//搜索关键字
		$this->assign('keyword', $keyword);
		//列表数据
		$this->assign('list', $list);

		if($return == true){
			return $list;
		}
		return $this->view($tpl);
	}
	/**
	* ajax分页
	* @param $list object 数据
	* @param $tpl  string 师徒模板
	* @param $list_field  String 视图显示字段
	* @return Object
	*/
	protected function ajax_next_page($list = '', $page = 1 , $tpl = '', $list_field = 'list'){
		$tpl        = $tpl ? $tpl : $this->request->action();

		$except  = $list->total() / $this->pagesize;

		$total_page = ceil($except);

		if($page >= $total_page){
			$is_hasmore = '';
		}else{
			$is_hasmore = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?page=' . ($page + 1);
		}

		if($this->isAjax()){
			$this->assign($list_field, $list);

			$data['html'] = $this->fetch($tpl . '_ajax_item');
			$data['page']['ajax_next_page'] = $is_hasmore;
			$this->success('获取数据成功！', '', $data);
		}
	}

}